package com.qf.mybatisplus.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Arrays;
import java.util.Properties;

/**
 * @ClassName: PropertiesUtil
 * @Author:Cola.Niu
 * @date:2020/3/19 11:27
 * @Version:v1.0
 * @description: 动态修改和读取配置文件的工具类
 */

public class PropertiesUtil {
    private static final Properties prop = new Properties();
    /**动态数据路径*/
    private static String path;
    /**是否是jar项目*/
    private static boolean flag;
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    /**
     * 通过类装载器 初始化Properties
     */
    public static void init() {
        path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        //转换成流
        try {
            //如果路径中含有中文，需要utf-8编码
            path = java.net.URLDecoder.decode(path,"utf-8");
            //如果是打包成jar,则取外部配置文件
            flag = path.contains("jar");
            if (flag){
                path = path.replace("file:","");
            }
            while (path.contains("jar")){
                path = path.substring(0,path.lastIndexOf("/"));
            }
            logger.info(path);
            InputStream is = new FileInputStream(path + (flag?"/config/datas.properties":"/datas.properties"));

            BufferedReader bf = new BufferedReader(new InputStreamReader(is, "GBK"));
            prop.load(bf);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.info(Arrays.toString(e.getStackTrace()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    static {
        init();
    }
    /**
     * 读取配置文件，返回字符串
     * @param key
     * @return
     */
    public static String read(String key){
        return prop.getProperty(key);
    }

    /**
     * 添加或修改配置文件
     * @param key
     * @param value
     * @return
     */
    public static boolean write(String key,String value){
        if (StringUtils.isSpace(key)||StringUtils.isSpace(value)){
            return false;
        }
        prop.setProperty(key, value);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream(path + (flag?"/config/datas.properties":"/datas.properties"));
            //将Properties中的属性列表（键和元素对）写入输出流
            prop.store(oFile, "");
            //init();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            logger.info(Arrays.toString(e.getStackTrace()));
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
